import * as types from './mutation-types'
import {shuffle} from '../common/js/shuffle'
import {playMode} from '../common/js/config'
function findIndex(list, song) {
  return list.findIndex((item) => {
    return item.id === song.id
  })
}

export const selectPlay = function ({commit, state}, {list, index, fullScreen, playing}) {
  commit(types.SET_SEQUENCE_LIST, list)
  if (state.mode === playMode.random) {
    let randomList = shuffle(list)
    commit(types.SET_PLAYING_LIST, randomList)
    index = findIndex(randomList, list[index])
  } else {
    commit(types.SET_PLAYING_LIST, list)
  }
  commit(types.SET_CURRENT_INDEX, index)
  commit(types.SET_FULL_SCREEN, fullScreen)
  commit(types.SET_PLAYING, playing)
}
export const playAllList = function ({commit, state}, {list}) {
  commit(types.SET_SEQUENCE_LIST, list)
  if (state.mode === playMode.random) {
    let randomList = shuffle(list)
    commit(types.SET_PLAYING_LIST, randomList)
  } else {
    commit(types.SET_PLAYING_LIST, list)
    commit(types.SET_MODE, playMode.sequence)
  }
  commit(types.SET_CURRENT_INDEX, 0)
  commit(types.SET_FULL_SCREEN, true)
  commit(types.SET_PLAYING, true)
}

export const deleteSong = function ({commit, state}, {list, index}) {
  let currentIndex = state.currentIndex
  let sequence = list.slice()
  let playingList = state.playingList.slice()
  sequence.splice(index, 1)
  commit(types.SET_SEQUENCE_LIST, sequence)
  index = findIndex(playingList, list[index])
  if (currentIndex > index || currentIndex === playingList.length) {
    currentIndex--
  }
  playingList.splice(index, 1)
  commit(types.SET_PLAYING_LIST, playingList)
  commit(types.SET_CURRENT_INDEX, currentIndex)
  if (!playingList.length) {
    commit(types.SET_PLAYING, false)
  }
}

export const deleteSongList = function ({commit}) {
  commit(types.SET_SEQUENCE_LIST, [])
  commit(types.SET_PLAYING_LIST, [])
  commit(types.SET_PLAYING, false)
  commit(types.SET_CURRENT_INDEX, -1)
}
